package com.example.service;
import com.example.DTO.DeepSeekRequest;
import com.example.DTO.DeepSeekResponse;
import com.example.DTO.Message;
import com.example.DTO.ProductDTO;
import com.example.entity.Product;
import com.example.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import java.util.List;
import org.springframework.http.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;

@Service
public class DeepSeekService {
    @Autowired
    private ProductMapper productMapper;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Resource
    private RestTemplate restTemplate;
    private static final String SYSTEM_PROMPT2 = "你是一个专业的商品长文本缩写助手，请将以下中文内容自动缩写，提取关键字，只需返回缩写结果，不要任何解释和格式。";
    private static final String SYSTEM_PROMPT = "你是一个专业的商品翻译助手，请将以下中文内容准确翻译成英文，只需返回翻译结果，不要任何解释和格式。";

    public Product tranSlate(int productId) throws IOException {
        Product product = productMapper.getById(productId);
        if (product == null) return null;
        // 翻译商品名称
        product.setName(translateWithRetry(product.getName(), 3));
        // 翻译商品描述
        product.setDescription(translateWithRetry(product.getDescription(), 3));
        return product;
    }

    private String translateWithRetry(String text, int retries) throws IOException {
        while (retries > 0) {
            try {
                return translateText(text);
            } catch (IOException e) {
                retries--;
                if (retries == 0) throw e;
            }
        }
        return text; // 保底返回原文
    }

    private String translateText(String text) throws IOException {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);

            DeepSeekRequest request = new DeepSeekRequest();
            request.setMessages(List.of(
                    new Message("system", SYSTEM_PROMPT),
                    new Message("user", text)
            ));

            ResponseEntity<DeepSeekResponse> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.POST,
                    new HttpEntity<>(request, headers),
                    DeepSeekResponse.class
            );

            if (response.getStatusCode().is2xxSuccessful() &&
                    response.getBody() != null &&
                    !response.getBody().getChoices().isEmpty()) {
                return response.getBody().getChoices().get(0).getMessage().getContent().trim();
            }
            throw new IOException("API request failed with status: " + response.getStatusCode());
        } catch (RestClientException e) {
            throw new IOException("API call failed: " + e.getMessage());
        }
    }

    public List<ProductDTO> abbreviation(String text) throws IOException {
        Product p=new Product();
        p.setName(text);
        List<ProductDTO> list= productMapper.selectByText(p);
        if (list == null) return null;
        for (ProductDTO productDTO : list) {
            productDTO.setDescription(abbreviationDescription(productDTO.getDescription()));
        }
        return list;
    }

    private String abbreviationDescription(String description)throws IOException {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(apiKey);

            DeepSeekRequest request = new DeepSeekRequest();
            request.setMessages(List.of(
                    new Message("system", SYSTEM_PROMPT2),
                    new Message("user", description)
            ));

            ResponseEntity<DeepSeekResponse> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.POST,
                    new HttpEntity<>(request, headers),
                    DeepSeekResponse.class
            );

            if (response.getStatusCode().is2xxSuccessful() &&
                    response.getBody() != null &&
                    !response.getBody().getChoices().isEmpty()) {
                return response.getBody().getChoices().get(0).getMessage().getContent().trim();
            }
            throw new IOException("API request failed with status: " + response.getStatusCode());
        } catch (RestClientException e) {
            throw new IOException("API call failed: " + e.getMessage());
        }
    }
}
